import React, { useState, useRef, useEffect, useMemo, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Layout, Card, Tabs, Typography, Space, Tag, Button, Input, Avatar, message, List, Badge, Spin, Tooltip, Drawer, Switch, Select } from 'antd';
import { authService } from '../lib/authService';

import {
  SendOutlined,
  DisconnectOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  CopyOutlined,
  RobotOutlined,
  BarChartOutlined,
  CommentOutlined,
  UserOutlined,
  StopOutlined,
  PictureOutlined,
  CloudOutlined,
  BulbOutlined,
  ArrowLeftOutlined,
  IdcardOutlined,
  CloseOutlined,
  CloudUploadOutlined,
  DeleteOutlined,
  WifiOutlined,
  SearchOutlined,
} from '@ant-design/icons';
import { localChatWebSocketService as chatWebSocketService, type WebSocketMessage, type ChatMessage } from '../lib/localWebSocketService';
import { localChatStorage, type LocalConversationState } from '../lib/localChatStorage';
import { streamApiService, StreamMessage } from '../lib/streamApi';

import { customerService } from '../services/customerService';
import { generateConversationId, type Customer } from '../types';
import AssetAllocationPage from '../components/AssetAllocationPage';
import MarketingScenarios from '../components/MarketingScenarios';
import CustomerProfilePage from '../components/CustomerProfilePage';
import { useCustomerContext } from '../context/CustomerContext';
import { uploadFile, validateFileType, validateFileSize, getFileTypeErrorMessage, getFileSizeErrorMessage } from '../lib/uploadApi';

import { formatFileSize } from '../utils/numberFormat';
import { ThinkingProcess } from '../components/ThinkingProcess';
import SmartSegmentedMessageRenderer, { SegmentContentChecker, MarkdownRenderer } from '../components/SmartSegmentedMessageRenderer';
import { getCustomerAvatar } from '../utils/avatarUtils';
import { formatTimestamp, getTimeAgo } from '../utils/timeUtils';
import { filterCustomersByRole } from '../utils/customerFilter';

const { Content, Sider } = Layout;
const { TextArea } = Input;
const { Title, Text } = Typography;
const { Option } = Select;

/**
 * SOP分析API的请求参数
 */
interface SopAnalysisRequest {
  query: string;
  mode: 'dynamic' | 'preset';
  session_id?: string | null;
  user_name: string;
  chain_id?: string;
}

/**
 * SOP分析API的响应节点
 */
interface SopAnalysisNode {
  id: string;
  name: string;
  type: string;
  status: 'pending' | 'active' | 'completed' | 'skipped';
  content: string;
}

/**
 * SOP分析API的响应结构
 */
interface SopAnalysisResponse {
  success: boolean;
  chain_id: string;
  chain_name: string;
  nodes: SopAnalysisNode[];
  error?: string;
}

/**
 * 后端实际返回的SOP分析结构
 */
interface ApiSopAnalysisResponse {
  success: boolean;
  chain_id: string;
  name: string; // 策略名称
  current_node: number; // 当前节点顺序
  full_chain: { // 节点数组
    order: number;
    node: string;
    stage: string;
  }[];
  error?: string;
}

// 客户列表数据类型
interface CustomerListItem {
  id: string;
  name: string;
  session_id: string;
  avatar: string; // 现在是头像URL
  lastMessage: string;
  unreadCount: number;
  tags: string[];
  lastMessageTime: number;
  isOnline: boolean;
}

// 1. 定义本地Message类型（仅用于本文件消息列表）
type LocalMessage = {
  id: number;
  type: 'client' | 'advisor';
  content: string;
  timestamp: string;
  sender: string;
  originalTimestamp?: number;
};

// 2. 定义全局唯一消息ID生成函数
const generateLocalMessageId = () => Date.now() + Math.floor(Math.random() * 10000);



// StreamingSegmentedRenderer组件，用于流式内容的实时分段渲染，与最终效果保持一致
function StreamingSegmentedRenderer({ 
  content, 
  onSendSegment, 
  onCopySegment 
}: { 
  content: string;
  onSendSegment: (segment: string) => void;
  onCopySegment: (segment: string) => void;
}) {
  // 判断段落是否只包含卡片占位符
  const isOnlyCardPlaceholder = useCallback((segment: string): boolean => {
    if (!segment || !segment.trim()) return false;
    
    // 检查是否只是卡片占位符格式 [CARD:...]
    const trimmedSegment = segment.trim();
    const cardPattern = /^\[CARD:[^\]]+\]$/;
    
    return cardPattern.test(trimmedSegment);
  }, []);

  // 实时分段处理
  const segments = useMemo(() => {
    if (!content || (!content.includes('[DIVIDER]') && !content.includes('\n\n'))) {
      return [content];
    }

    return content
      .split(/\[DIVIDER\]|\n\n+/)
      .map(part => part.trim())
      .filter(part => part.length > 0);
  }, [content]);

  // 分析哪些段落需要检查器，哪些可以直接渲染
  const segmentInfo = useMemo(() => {
    return segments.map((segment, index) => ({
      segment,
      index,
      needsChecker: isOnlyCardPlaceholder(segment)
    }));
  }, [segments, isOnlyCardPlaceholder]);

  // 只跟踪需要检查器的段落的有效性
  const [segmentValidities, setSegmentValidities] = useState<{[key: number]: boolean}>({});

  // 处理段落有效性变化
  const handleValidityChange = useCallback((index: number, isValid: boolean) => {
    setSegmentValidities(prev => ({
      ...prev,
      [index]: isValid
    }));
  }, []);

  // 初始化需要检查器的段落的有效性状态
  useEffect(() => {
    const initialValidities: {[key: number]: boolean} = {};
    segmentInfo.forEach(({ index, needsChecker }) => {
      if (needsChecker) {
        initialValidities[index] = true; // 默认为有效，等待检查器验证
      }
    });
    setSegmentValidities(initialValidities);
  }, [segmentInfo]);

  // 过滤出需要渲染的段落
  const segmentsToRender = useMemo(() => {
    return segmentInfo.filter(({ index, needsChecker }) => {
      if (!needsChecker) {
        // 不需要检查器的段落直接渲染
        return true;
      } else {
        // 需要检查器的段落，根据检查结果决定是否渲染
        return segmentValidities[index] !== false;
      }
    });
  }, [segmentInfo, segmentValidities]);

  // 如果只有一个分段，返回简单的渲染
  if (segments.length <= 1) {
    return <MarkdownRenderer content={content} />;
  }

  // 如果所有段落都无效，不渲染任何内容
  if (segmentsToRender.length === 0) {
    return null;
  }

  // 多分段时，每个分段都有独立的消息框和按钮（与最终效果一致）
  return (
    <div className="streaming-segmented-content space-y-3">
      {/* 只为需要检查的段落创建隐藏的内容检查器 */}
      {segmentInfo
        .filter(({ needsChecker }) => needsChecker)
        .map(({ segment, index }) => (
          <SegmentContentChecker
            key={`checker-${index}`}
            content={segment}
            onValidityChange={(isValid) => handleValidityChange(index, isValid)}
          />
        ))
      }
      
      {/* 只渲染有效的段落 */}
      {segmentsToRender.map(({ segment, index }) => {
        // 其他内容正常渲染在消息框中
        return (
          <div key={index} className="max-w-xs px-3 py-2 rounded-lg bg-white text-gray-800 border border-gray-200">
            <div className="text-sm prose prose-sm max-w-none">
              <MarkdownRenderer content={segment} />
            </div>
            <div className="flex gap-1 mt-2">
              <Button
                type="primary"
                size="small"
                onClick={() => onSendSegment(segment)}
                icon={<SendOutlined />}
              >
                发送
              </Button>
              <Button
                size="small"
                onClick={() => onCopySegment(segment)}
                icon={<CopyOutlined />}
              >
                复制
              </Button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

export default function ConversationPage() {
  const navigate = useNavigate();
  const { selectedCustomer, setSelectedCustomer } = useCustomerContext();
  const [currentCustomer, setCurrentCustomer] = useState<Customer | null>(selectedCustomer);
  const currentCustomerId = selectedCustomer?.id?.toString();
  const currentCustomerName = currentCustomer?.name || '未知用户';

  // 获取当前登录的理财师信息
  const [currentManager, setCurrentManager] = useState<{id: string, name: string, loginTime: string} | null>(null);
  
  // 客户数据
  const [allCustomers, setAllCustomers] = useState<Customer[]>([]);

  // 检查登录状态
  useEffect(() => {
    // ProtectedRoute确保了只有登录用户能进入，所以这里可以直接获取
    const manager = authService.getManager();
    if(manager) {
      setCurrentManager(manager);
    }
  }, []);

  // 获取所有客户
  useEffect(() => {
    const fetchCustomers = async () => {
      try {
        const customers = await customerService.getAllCustomers();
        setAllCustomers(customers);
      } catch (error) {
        message.error('加载客户列表失败');
      } finally {
      }
    };
    fetchCustomers();
  }, []);

  // 根据登录的理财师过滤客户
  useEffect(() => {
    if (!currentManager || allCustomers.length === 0) {
      return;
    }
  }, [currentManager, allCustomers]);

  const [messageInput, setMessageInput] = useState('');
  // 替换 useState<Message[]> 为 useState<LocalMessage[]>
  const [messages, setMessages] = useState<LocalMessage[]>([]);
  const [activeTab, setActiveTab] = useState('business-guidance');
  const [isWebSocketConnected, setIsWebSocketConnected] = useState(false);
  const [rightPanelVisible, setRightPanelVisible] = useState(true);
  const [rightPanelWidth, setRightPanelWidth] = useState(() => {
    const saved = localStorage.getItem('rightPanelWidth');
    return saved ? parseInt(saved, 10) : 550;
  });
  const [isDragging, setIsDragging] = useState(false);

  // SOP经营引导相关状态
  const [isDeepSop, setIsDeepSop] = useState(true); // Deep SOP模式开关
  const [sopAnalysisResult, setSopAnalysisResult] = useState<SopAnalysisResponse | null>(null); // SOP分析结果
  const [isSopLoading, setIsSopLoading] = useState(false); // SOP加载状态
  const [selectedChainId, setSelectedChainId] = useState<string>('');

  // 经营引导相关状态 (保留用于兼容性)
  // const [aiChatHistory, setAiChatHistory] = useState<Array<{type: 'user' | 'ai', content: string, timestamp: string, files?: any[], isLoading?: boolean, loadingId?: string}>>([]);
  const [aiStreamReply, setAiStreamReply] = useState<string>('');
  const [aiChatInput, setAiChatInput] = useState('');
  
  // 添加文件上传状态
  const [uploadStatus, setUploadStatus] = useState<{
    isUploading: boolean;
    fileName: string;
  }>({ isUploading: false, fileName: '' });
  
  // 区分自动回复和手动对话的状态
  const [isAutoReplying, setIsAutoReplying] = useState(false); // 是否正在自动回复客户
  const [isManualChatting, setIsManualChatting] = useState(false); // 是否在手动与AI对话
  const [autoReplyStreamContent, setAutoReplyStreamContent] = useState<string>(''); // 自动回复的流式内容
  
  
  // 添加reasoning阶段专门的状态
  const [isAutoReplyReasoning, setIsAutoReplyReasoning] = useState(false); // 自动回复是否在reasoning阶段
  const [isManualReasoning, setIsManualReasoning] = useState(false); // 手动对话是否在reasoning阶段
  
  // 等待第一个reasoning chunk的loading状态
  const [isWaitingForAutoThinking, setIsWaitingForAutoThinking] = useState(false); // 自动回复等待thinking
  const [isWaitingForManualThinking, setIsWaitingForManualThinking] = useState(false); // 手动对话等待thinking
  
  // 思考过程内容状态（简化架构）
  const [autoReplyThinkingContent, setAutoReplyThinkingContent] = useState('');
  const [manualThinkingContent, setManualThinkingContent] = useState('');

  // ==================== AiChat状态设计 ====================
  interface AiChatState {
    isActive: boolean;           // 替代 isAutoReplying + isManualChatting  
    type: 'auto' | 'manual' | null;  // 当前AI聊天类型
    hasReceivedFirstChunk: boolean;  // 是否已收到第一个LLM chunk
    isReasoning: boolean;        // 是否在reasoning阶段
    isWaitingForThinking: boolean;   // 是否等待thinking开始
    thinkingContent: string;     // thinking内容
    streamContent: string;       // 流式内容
  }

  // 初始状态工厂函数
  const createInitialAiChatState = (): AiChatState => ({
    isActive: false,
    type: null,
    hasReceivedFirstChunk: false,
    isReasoning: false,
    isWaitingForThinking: false,
    thinkingContent: '',
    streamContent: ''
  });

  // ==================== 统一的AiChat状态管理 ====================
  const [aiChatState, setAiChatState] = useState<AiChatState>(createInitialAiChatState());
  
  // 状态管理函数
  const updateAiChatState = (updates: Partial<AiChatState>) => {
    setAiChatState(prev => ({ ...prev, ...updates }));
  };
  
  const resetAiChatState = (type?: 'auto' | 'manual') => {
    const initialState = createInitialAiChatState();
    if (type) {
      initialState.type = type;
    }
    setAiChatState(initialState);
  };

  // ==================== 统一的Thinking回调管理 ====================
  const createThinkingCallbacks = (chatType: 'auto' | 'manual') => {
    if (deepThinkingEnabled) return null; // 反转逻辑：true时使用mock，不需要回调
    
    return {
      onThinkingStart: () => {
        console.log(`${chatType} thinking started`);
        updateAiChatState({ 
          isWaitingForThinking: false, 
          isReasoning: true,
          thinkingContent: ''
        });
      },
      onThinkingChunk: (_chunk: string, accumulated: string) => {
        // 🔥 关键：每个reasoning chunk都要实时显示在UI上
        updateAiChatState({ thinkingContent: accumulated });
      },
      onThinkingComplete: (fullThinking: string) => {
        // 🔥 美化输出accumulated thinking内容
        console.log('%c🧠 AI Reasoning Complete', 'color: #4CAF50; font-weight: bold; font-size: 14px;');
        console.log('%c━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'color: #9E9E9E;');
        console.log('%c' + fullThinking, 'color: #2c3e50; font-size: 13px; line-height: 1.6; font-family: "SF Mono", "Monaco", "Consolas", "Liberation Mono", "Courier New", monospace; background-color: #f8f9fa; padding: 8px; border-radius: 4px; display: block; white-space: pre-wrap;');
        console.log('%c━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━', 'color: #9E9E9E;');
        console.log('%c✨ End of Reasoning', 'color: #FF9800; font-weight: bold;');
        
        // 🔥 thinking完成后保持内容显示，只是标记reasoning阶段结束
        updateAiChatState({ 
          thinkingContent: fullThinking,
          isReasoning: false 
        });
      },
      onLlmStart: () => {
        console.log(`${chatType} LLM started`);
        // 🔥 LLM开始时才清空thinking内容，因为LLM内容会接管显示
        updateAiChatState({ 
          isReasoning: false,
          thinkingContent: '' 
        });
      }
    };
  };

  // ==================== 保存面板宽度到localStorage ====================
  useEffect(() => {
    localStorage.setItem('rightPanelWidth', rightPanelWidth.toString());
  }, [rightPanelWidth]);

  // ==================== 右侧面板拖拽调整宽度 ====================
  const handleMouseDown = (e: React.MouseEvent) => {
    e.preventDefault();
    setIsDragging(true);
    
    const handleMouseMove = (e: MouseEvent) => {
      const containerRect = document.querySelector('.conversation-page')?.getBoundingClientRect();
      if (containerRect) {
        const newWidth = containerRect.right - e.clientX;
        // 限制宽度范围：最小300px，最大800px
        const clampedWidth = Math.max(300, Math.min(800, newWidth));
        setRightPanelWidth(clampedWidth);
      }
    };
    
    const handleMouseUp = () => {
      setIsDragging(false);
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mouseup', handleMouseUp);
    };
    
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);
  };

  // ==================== 统一的AI聊天处理 ====================
  const handleUnifiedAiChat = async (params: {
    message: string;
    type: 'auto' | 'manual';
    messageType?: 'customer' | 'user';
    enableSop?: boolean;
    isDeep?: boolean;
    chainId?: string;
  }) => {
    // 1. 初始化状态
    updateAiChatState({
      isActive: true,
      type: params.type,
      hasReceivedFirstChunk: false,
      streamContent: '',
      isWaitingForThinking: !deepThinkingEnabled, // 反转逻辑：false时等待thinking
      isReasoning: false,
      thinkingContent: ''
    });

    // 2. 添加用户消息到队列
    const messageType = params.messageType || (params.type === 'auto' ? 'customer' : 'user');
    const messageId = Date.now().toString() + `_${messageType}`;
    setAiAssistantQueue(prev => [...prev, {
      type: 'chat' as const,
      data: {
        type: messageType as 'user' | 'ai' | 'customer',
        content: params.message,
        timestamp: new Date().toISOString(),
        files: params.type === 'manual' && aiUploadedFiles.length > 0 ? [...aiUploadedFiles] : undefined
      },
      id: messageId,
      time: Date.now()
    }].sort((a, b) => a.time - b.time));

    // 3. SOP分析 (仅auto且启用时，完全异步)
    if (params.type === 'auto' && params.enableSop) {
      performSopAnalysisAsync(params.message, params.isDeep, params.chainId);
    }

    // 4. 清空手动输入框
    if (params.type === 'manual') {
      setAiChatInput('');
    }

    // 5. 滚动到底部
    smartScrollAiChat();

    // 6. 设置thinking callbacks
    thinkingCallbacksRef.current = createThinkingCallbacks(params.type);

    // 7. 提取docIds
    const docIds = aiUploadedFiles.map(file => file.docId).filter(Boolean);

    // 8. 执行流式API调用
    await processAiStream(params.message, docIds, params.type);
  };

  // ==================== 统一的流式处理函数 ====================
  const processAiStream = async (message: string, docIds: string[], type: 'auto' | 'manual') => {
    try {
      await streamApiService.sendMessageStream(
        message,
        // onChunk 回调 - 使用防抖优化性能
        (chunk: string, accumulated: string, phase?: 'reasoning' | 'llm') => {
          // 只有在LLM阶段（或没有phase信息时）才设置已收到第一个chunk
          if (chunk && chunk.trim() && !aiChatState.hasReceivedFirstChunk && (phase === 'llm' || !phase)) {
            updateAiChatState({ hasReceivedFirstChunk: true });
            // 如果还在等待thinking，说明后端没有reasoning chunk，立即清除等待状态
            if (aiChatState.isWaitingForThinking) {
              updateAiChatState({
                isWaitingForThinking: false,
                thinkingContent: '',
                isReasoning: false
              });
            }
          }
          // 只在LLM阶段（或没有phase信息时）更新流式内容
          if (phase === 'llm' || !phase) {
            updateAiChatState({ streamContent: accumulated });
            smartScrollAiChat();
          }
        },
        // onComplete 回调
        (fullMessage: StreamMessage) => {
          // 重置状态
          resetAiChatState();

          // 直接添加完整回复到消息队列
          const completedChatId = Date.now().toString() + `_${type}_reply`;
          setAiAssistantQueue((prev) => [...prev, {
            type: 'chat' as const,
            data: {
              type: 'ai' as const,
              content: fullMessage.text,
              timestamp: new Date().toISOString(),
              firstTokenTime: fullMessage.metadata?.firstTokenTime,
              totalDelta: fullMessage.metadata?.totalDelta
            },
            id: completedChatId,
            time: Date.now()
          }].sort((a, b) => a.time - b.time));

          // 清空流式内容 - 使用setTimeout确保在下一个渲染周期清空
          createSafeTimeout(() => {
            updateAiChatState({ streamContent: '' });
          }, 0);

          // 完成后滚动到底部
          debouncedScrollAiChatToBottom();
        },
        // onError 回调
        (error: string) => {
          console.error(`❌ ${type}聊天失败:`, error);
          
          // 重置状态
          resetAiChatState();

          // 添加错误消息到队列
          const errorChatId = Date.now().toString() + `_${type}_error`;
          setAiAssistantQueue((prev) => [...prev, {
            type: 'chat' as const,
            data: {
              type: 'ai' as const,
              content: '抱歉，AI回复失败，请稍后再试。',
              timestamp: new Date().toISOString()
            },
            id: errorChatId,
            time: Date.now()
          }].sort((a, b) => a.time - b.time));

          scrollAiChatToBottom();
        },
        currentCustomer?.name,
        currentCustomer?.session_id,
        docIds,
        undefined, // service_id
        undefined, // background
        !deepThinkingEnabled, // 反转逻辑：false时enableThinking=true
        thinkingCallbacksRef.current // 传递思考过程回调
      );
    } catch (error) {
      // 重置状态
      resetAiChatState();

      // 添加错误消息到队列
      const catchErrorChatId = Date.now().toString() + `_${type}_catch_error`;
      setAiAssistantQueue((prev) => [...prev, {
        type: 'chat' as const,
        data: {
          type: 'ai' as const,
          content: '抱歉，AI回复失败，请稍后再试。',
          timestamp: new Date().toISOString()
        },
        id: catchErrorChatId,
        time: Date.now()
      }].sort((a, b) => a.time - b.time));

      console.error(`Failed to send ${type} chat:`, error);
      scrollAiChatToBottom();
    }
  };

  // SOP异步分析函数
  const performSopAnalysisAsync = (message: string, isDeep?: boolean, chainId?: string) => {
    if (!currentCustomer || !currentManager) return;
    
    // 🚀 Fire and forget - 异步执行，不阻塞主流程
    Promise.resolve().then(async () => {
      setIsSopLoading(true);
      try {
        const params: SopAnalysisRequest = isDeep ? 
        {
          query: message,
          mode: 'dynamic',
          session_id: currentCustomer.session_id || '',
          user_name: currentCustomer.name,
        } :
        {
          query: message,
          mode: 'preset',
          session_id: currentCustomer.session_id || '',
          user_name: currentCustomer.name,
          chain_id: chainId,
        };
        
        const response = await fetch('/langchain-backend/sop/analyze', {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(params)
        });

        if (!response.ok) {
          const errorData = await response.json().catch(() => null);
          throw new Error(`HTTP error! status: ${response.status}, message: ${errorData?.detail || response.statusText}`);
        }

        const result: ApiSopAnalysisResponse = await response.json();
        
        // 检查组件是否还在挂载状态
        if (!isMountedRef.current) return;
        
        if (result.success && result.full_chain) {
          const transformedResult: SopAnalysisResponse = {
            success: true,
            chain_id: result.chain_id,
            chain_name: result.name,
            nodes: result.full_chain.map(apiNode => ({
              id: apiNode.order.toString(),
              name: apiNode.node,
              type: apiNode.stage,
              status: apiNode.order === result.current_node
                ? 'active'
                : apiNode.order < result.current_node
                  ? 'completed'
                  : 'pending',
              content: '',
            })),
          };
          setSopAnalysisResult(transformedResult);
        } else if (result.full_chain.length === 0) {
          setSopAnalysisResult(null);
        }
      } catch (error) {
        console.warn('SOP分析失败（不影响AI聊天）:', error);
      } finally {
        if (isMountedRef.current) {
          setIsSopLoading(false);
        }
      }
    });
  };

  // AI对话增强功能状态
  const [deepThinkingEnabled, setDeepThinkingEnabled] = useState(true);
  const [aiUploadedFiles, setAiUploadedFiles] = useState<any[]>([]);

  // 统一的AI助手消息队列（包含对话历史、产品推荐等，按时间排序）
  type AiAssistantItem =
    | { type: 'chat', data: { type: 'user' | 'ai' | 'customer', content: string, timestamp: string, files?: any[], isLoading?: boolean, loadingId?: string, firstTokenTime?: number, totalDelta?: number }, id: string, time: number };

  const [aiAssistantQueue, setAiAssistantQueue] = useState<AiAssistantItem[]>([]);

  // 滚动状态管理
  const [userScrolledUp, setUserScrolledUp] = useState(false);
  const [chatScrolledUp, setChatScrolledUp] = useState(false);

  // 客户列表相关状态
  const [customerList, setCustomerList] = useState<CustomerListItem[]>([]);
  const [showCustomerList, setShowCustomerList] = useState(true);

  // Loading状态
  const [isLoadingMessages, setIsLoadingMessages] = useState(false);

  // 引用
  const chatMessagesRef = useRef<HTMLDivElement>(null);
  const aiChatRef = useRef<HTMLDivElement>(null);
  const aiFileInputRef = useRef<HTMLInputElement>(null);
  const thinkingCallbacksRef = useRef<any>(null); // 思考过程回调引用

  // 将Customer转换为CustomerListItem
  const convertToCustomerListItem = (customer: Customer): CustomerListItem => {
    // 从localStorage获取conversation state
    const conversationStates = localChatStorage.getConversations();
    const customerId = customerService.getCustomerWebSocketId(customer); // 使用统一的WebSocket用户ID格式
    const conversationState = conversationStates.find((cs: LocalConversationState) => cs.c_user_id === customerId);
    
    return {
      id: customer.id?.toString() || '',
      name: customer.name || '',
      session_id: customer.session_id || '',
      avatar: getCustomerAvatar(customer.id || 0, customer.name),
      lastMessage: conversationState?.last_message_content || '等待发送消息...',
      unreadCount: conversationState?.b_user_unread_count || 0,
      tags: [customer.risk_level, customer.investment_experience].filter(Boolean),
      lastMessageTime: conversationState ? new Date(conversationState.last_message_time.endsWith('Z') ? conversationState.last_message_time : conversationState.last_message_time + 'Z').getTime() : 0,
      isOnline: true
    };
  };

  // 处理消息内容，将卡片占位符替换为 "[卡片]"
  const formatMessageForDisplay = (message: string): string => {
    if (!message) return message;
    
    // 检查是否包含卡片占位符格式 [CARD:...]
    const cardPattern = /\[CARD:[^\]]+\]/g;
    if (cardPattern.test(message)) {
      return message.replace(cardPattern, '[卡片]');
    }
    
    return message;
  };

  // 处理客户列表点击
  const handleCustomerListClick = async (customerId: string) => {
    if (customerId !== currentCustomerId) {
      setIsLoadingMessages(true);
      
      // 立即清空消息历史，避免旧客户的卡片组件继续发送API请求
      setMessages([]);
      
      setAiUploadedFiles([]);
      setClearAssetFiles(true);
      setAllocationPageKey(prev => prev + 1);
      
      // 清空AI助手相关状态
      setAiAssistantQueue([]);
      setAiStreamReply('');
      setIsManualChatting(false);
      setIsAutoReplying(false);
      setAutoReplyStreamContent('');
      setAiChatInput('');
      setIsAutoReplyReasoning(false); // 重置自动回复reasoning状态
      setIsManualReasoning(false); // 重置手动对话reasoning状态
      setAutoReplyThinkingContent(''); // 重置思考内容
      setManualThinkingContent(''); // 重置思考内容
      setIsWaitingForAutoThinking(false); // 重置等待思考状态
      setIsWaitingForManualThinking(false); // 重置等待思考状态
      
      // 停止正在进行的流式API请求
      streamApiService.stopStream();

                // 找到目标客户的会话信息，标记为已读
          const targetCustomer = customerList.find(customer => customer.id === customerId);
          if (targetCustomer && targetCustomer.unreadCount > 0) {
            try {
              // 获取WebSocket用户ID - 使用统一的格式
              const customer = customerService.getCustomerById(customerId);
              const wsUserId = customerService.getCustomerWebSocketId(customer);
              if (wsUserId) {
                const conversationId = generateConversationId(currentManager?.id || '', wsUserId);
                await chatWebSocketService.markConversationRead(conversationId);

            // 更新本地状态
            setCustomerList(prevCustomers => {
              return prevCustomers.map(customer => {
                if (customer.id === customerId) {
                  return {
                    ...customer,
                    unreadCount: 0
                  };
                }
                return customer;
              });
            });
          }
        } catch (error) {
          console.error('Failed to mark conversation as read:', error);
        }
      }

      // 从customerService获取完整的客户数据并设置到上下文中
      try {
        const customer = customerService.getCustomerById(customerId);
        if (customer) {
          setSelectedCustomer(customer);
        }
      } catch (error) {
        console.error('Failed to get customer data:', error);
      }

      navigate(`/conversation`);
    }
  };

  // ==================== useEffect优化区域 ====================
  // 将原本的巨大useEffect拆分为多个独立的useEffect，每个有明确的职责和合理的依赖
  // 这样可以减少不必要的重渲染，提高性能，并且更易于理解和维护
  
  // 监听selectedCustomer的变化
  useEffect(() => {
    if (!selectedCustomer) return;
    
    setCurrentCustomer(selectedCustomer);
    
    // 立即清空消息历史，避免旧客户的卡片组件继续发送API请求
    setMessages([]);
    
    // 当客户变化时，清空AI助手相关状态
    setAiAssistantQueue([]);
    setAiStreamReply('');
    setIsManualChatting(false);
    setIsAutoReplying(false);
    setAutoReplyStreamContent('');
    setAiChatInput('');
    setIsAutoReplyReasoning(false); // 重置自动回复reasoning状态
    setIsManualReasoning(false); // 重置手动对话reasoning状态
    setAutoReplyThinkingContent(''); // 重置思考内容
    setManualThinkingContent(''); // 重置思考内容
    setIsWaitingForAutoThinking(false); // 重置等待思考状态
    setIsWaitingForManualThinking(false); // 重置等待思考状态
    
    // 停止正在进行的流式API请求
    streamApiService.stopStream();

  }, [selectedCustomer]);

  // 1. 检查登录状态
  useEffect(() => {
    const manager = authService.getManager();
    if (manager) {
      setCurrentManager(manager);
    }
  }, []);

  // 2. 初始化客户数据
  useEffect(() => {
    const initializeCustomerData = async () => {
      try {
        await customerService.getAllCustomers();

        // 如果已经有选中的客户，直接使用
        if (selectedCustomer) {
          setCurrentCustomer(selectedCustomer);
          return;
        }

        // 否则尝试从customerService获取客户数据
        if (currentCustomerId) {
          const customer = customerService.getCustomerById(currentCustomerId);
          if (customer) {
            setCurrentCustomer(customer);
            return;
          }
        }

        // 如果找不到指定客户，使用第一个客户作为默认
        const allCustomers = customerService.searchCustomers('');
        if (allCustomers.length > 0) {
          setCurrentCustomer(allCustomers[0]);
        }
      } catch (error) {
        console.error('Failed to initialize customer data:', error);
      }
    };

    initializeCustomerData();
  }, [selectedCustomer, currentCustomerId]);

  // 4. 加载消息历史
  useEffect(() => {
    const loadMessageHistory = async () => {
      setIsLoadingMessages(true);
      const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
      if (!wsUserId) {
        setMessages([]);
        setIsLoadingMessages(false);
        createSafeTimeout(() => scrollToBottom(), 300);
        return;
      }
      
      const conversationId = generateConversationId(currentManager?.id || '', wsUserId);
      try {
        const chatMessages = await chatWebSocketService.getConversationMessages(conversationId);
        const frontendMessages = chatMessages
          .map((chatMsg: ChatMessage): LocalMessage => ({
            id: parseInt(chatMsg.id) || generateLocalMessageId(),
            type: chatMsg.sender_id === (currentManager?.id || '') ? 'advisor' : 'client',
            content: chatMsg.content,
            timestamp: chatMsg.timestamp.endsWith('Z') ? chatMsg.timestamp : chatMsg.timestamp + 'Z', // 保持ISO格式
            sender: chatMsg.sender_id === (currentManager?.id || '') ? (currentManager?.name || '理财师') : currentCustomerName,
            originalTimestamp: new Date(chatMsg.timestamp.endsWith('Z') ? chatMsg.timestamp : chatMsg.timestamp + 'Z').getTime()
          }))
          .sort((a, b) => (a.originalTimestamp || 0) - (b.originalTimestamp || 0));
        setMessages(frontendMessages);
        createSafeTimeout(() => scrollToBottom(), 300);
      } catch (error) {
        console.error('Failed to load message history:', error);
        setMessages([]);
      } finally {
        setIsLoadingMessages(false);
      }
    };

    if (currentCustomer && currentManager) {
      loadMessageHistory();
    }
  }, [currentCustomer, currentManager, currentCustomerName]);

  // 5. 设置WebSocket监听器
  useEffect(() => {
    const handleWebSocketMessage = (wsMessage: WebSocketMessage) => {
      // 只处理当前选定客户的消息
      const customerWsId = customerService.getCustomerWebSocketId(currentCustomer);
      if (!customerWsId || wsMessage.sender_id !== customerWsId) {
        return;
      }

      if (wsMessage.type === 'message' && wsMessage.sender_id && wsMessage.content) {
        const messageTimestamp = wsMessage.timestamp ? wsMessage.timestamp.endsWith('Z') ? wsMessage.timestamp : wsMessage.timestamp + 'Z' : new Date().toISOString();

        const newMessage: LocalMessage = {
          id: generateLocalMessageId(),
          type: 'client',
          content: wsMessage.content,
          timestamp: messageTimestamp, // 使用ISO格式
          sender: currentCustomerName,
          originalTimestamp: new Date(messageTimestamp).getTime()
        };

        setMessages(prev => [...prev, newMessage]);
        message.info(`收到来自${currentCustomerName}的新消息`);

        // 智能滚动到新消息
        createSafeTimeout(() => smartScrollChat(), 100);

        // 收到消息后立即标记为已读
        const conversationId = generateConversationId(currentManager?.id || '', customerWsId);
        chatWebSocketService.markConversationRead(conversationId);
        setCustomerList(prev => prev.map(c =>
          c.id === customerWsId ? { ...c, unreadCount: 0 } : c
        ));

        handleAutoReplyToCustomer(wsMessage.content, isDeepSop, selectedChainId);
      }

      // 更新客户列表
      if (wsMessage.sender_id !== (currentManager?.id || '')) {
        createSafeTimeout(() => {
          updateCustomerList();
        }, 300);
      }
    };

    chatWebSocketService.addMessageListener(handleWebSocketMessage);
    
    return () => {
      chatWebSocketService.removeMessageListener(handleWebSocketMessage);
    };
  }, [currentCustomer, currentManager, currentCustomerName,isDeepSop, selectedChainId]);

  // 6. 更新客户列表的独立函数
  const updateCustomerList = useCallback(() => {
    try {
      const allCustomers = customerService.searchCustomers('');
      const manager = authService.getManager();

      // 根据用户角色过滤客户列表
      const filteredCustomers = filterCustomersByRole(allCustomers, manager?.name);

      const convertedCustomers = filteredCustomers.map(convertToCustomerListItem);
      
      // 按最后消息时间排序，杨丽置顶
      convertedCustomers.sort((a, b) => {
        if (a.name === '杨丽') return -1;
        if (b.name === '杨丽') return 1;
        
        // 其他客户按最后消息时间排序（最新的在前）
        return (b.lastMessageTime || 0) - (a.lastMessageTime || 0);
      });
      
      setCustomerList(convertedCustomers);
    } catch (error) {
      console.error('Failed to update customer list:', error);
    }
  }, []);

  // 7. 初始加载客户列表
  useEffect(() => {
    const loadInitialCustomerList = async () => {
      try {
        await customerService.initialize();
        updateCustomerList();
      } catch (error) {
        console.error('Failed to load initial customer list:', error);
        setCustomerList([]);
      }
    };

    loadInitialCustomerList();
  }, [updateCustomerList]);

  // 8. 客户列表更新监听器
  useEffect(() => {
    const handleConversationUpdate = () => {
      updateCustomerList();
    };

    chatWebSocketService.addConversationUpdateListener(handleConversationUpdate);
    
    return () => {
      chatWebSocketService.removeConversationUpdateListener(handleConversationUpdate);
    };
  }, [updateCustomerList]);

  // 9. 定期检查连接状态
  useEffect(() => {
    const checkConnection = () => {
      setIsWebSocketConnected(chatWebSocketService.isConnected());
    };

    // 初始检查
    checkConnection();
    
    const connectionCheckInterval = setInterval(checkConnection, 2000);

    return () => {
      clearInterval(connectionCheckInterval);
    };
  }, []);

  // 10. 设置全局函数
  useEffect(() => {
    (window as any).sendAllocationToUser = (allocationData: any) => {
      try {
        const allocationMessage: LocalMessage = {
          id: generateLocalMessageId(),
          type: 'advisor',
          content: `已为您推荐资产配置方案：${allocationData.title}`,
          timestamp: new Date().toISOString(), // 使用ISO格式
          sender: currentManager?.name || '理财师',
          originalTimestamp: Date.now()
        };

        setMessages(prev => [...prev, allocationMessage]);

        const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
        if (wsUserId && chatWebSocketService.isConnected()) {
          chatWebSocketService.sendChatMessage(wsUserId, allocationMessage.content);
        }

        message.success('资产配置方案已发送给客户');
        createSafeTimeout(() => forceScrollChatToBottom(), 100);
      } catch (error) {
        console.error('发送资产配置失败:', error);
        message.error('发送资产配置失败');
      }
    };

    (window as any).buyAllocation = (allocationData: any) => {
      try {
        message.info(`正在为您配置资产组合：${allocationData.title}`);
      } catch (error) {
        console.error('购买资产配置失败:', error);
        message.error('购买资产配置失败');
      }
    };

    return () => {
      delete (window as any).sendAllocationToUser;
      delete (window as any).buyAllocation;
    };
  }, [currentCustomer, currentManager,isDeepSop]);

  // 处理发送消息
  const handleSendMessage = async () => {
    if (!messageInput.trim()) return;

    const newMessage: LocalMessage = {
      id: generateLocalMessageId(),
      type: 'advisor',
      content: messageInput.trim(),
      timestamp: new Date().toISOString(), // 使用ISO格式
      sender: currentManager?.name || '理财师',
      originalTimestamp: Date.now()
    };

    // 添加到消息列表
    setMessages(prev => [...prev, newMessage]);

    // 通过WebSocket发送给客户
    const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
    if (wsUserId && chatWebSocketService.isConnected()) {
      chatWebSocketService.sendChatMessage(wsUserId, messageInput.trim());
    }

    // 清空输入
    setMessageInput('');

    // 强制滚动到底部（顾问发送消息时）
    createSafeTimeout(() => forceScrollChatToBottom(), 100);
  };

  // 自动回复客户的处理函数 - 重构后使用统一处理
  const handleAutoReplyToCustomer = async (messageContent: string, isDeep: boolean, chainId: string) => {
    await handleUnifiedAiChat({
      message: messageContent,
      type: 'auto',
      messageType: 'customer',
      enableSop: true,
      isDeep,
      chainId
    });
  };


  // AI助手对话发送 - 重构后使用统一处理
  const handleAiChatSend = async () => {
    if (!aiChatInput.trim()) return;

    await handleUnifiedAiChat({
      message: aiChatInput.trim(),
      type: 'manual',
      messageType: 'user',
      enableSop: false
    });
  };



  // 发送AI回复给客户
  const handleSendAiReply = (reply: string) => {
    const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
    if (wsUserId && chatWebSocketService.isConnected()) {
      chatWebSocketService.sendChatMessage(wsUserId, reply);

                  // 添加到消息列表
            const newMessage: LocalMessage = {
              id: generateLocalMessageId(),
              type: 'advisor',
              content: reply,
              timestamp: new Date().toISOString(), // 使用ISO格式
              sender: currentManager?.name || '理财师',
              originalTimestamp: Date.now()
            };

      setMessages(prev => [...prev, newMessage]);
      message.success('AI回复已发送给客户');
      createSafeTimeout(() => forceScrollChatToBottom(), 100);
    } else {
      message.error('WebSocket连接断开，无法发送消息');
    }
  };

  // 复制AI回复
  const handleCopyAiReply = (content: string) => {
    navigator.clipboard.writeText(content);
    message.success('已复制到剪贴板');
  };

  // 处理SOP节点点击事件 - 重构后使用统一处理
  const handleSopNodeClick = async (nodeName: string) => {
    console.log('SOP节点点击:', nodeName);

    // 构建SOP节点消息内容
    const sopMessage = `请根据SOP策略"${nodeName}"为我提供详细的操作指导和话术建议。`;
    const displayMessage = `[SOP策略] ${nodeName}`;

    // 先添加显示的用户SOP节点消息到消息队列
    const userSopChatId = Date.now().toString() + '_sop_user';
    setAiAssistantQueue(prev => [...prev, {
      type: 'chat' as const,
      data: {
        type: 'user' as const,
        content: displayMessage,
        timestamp: new Date().toISOString(),
        files: aiUploadedFiles.length > 0 ? [...aiUploadedFiles] : undefined
      },
      id: userSopChatId,
      time: Date.now()
    }].sort((a, b) => a.time - b.time));

    // 使用统一处理函数处理实际的SOP消息
    await handleUnifiedAiChat({
      message: sopMessage,
      type: 'manual',
      messageType: 'user',
      enableSop: false
    });
  };

  // 停止AI回复（仅停止手动对话，不影响自动回复）
  const handleStopAiReply = () => {
    if (aiChatState.isActive && aiChatState.type === 'manual') {
      // 停止流式请求
      streamApiService.stopStream();

      // 如果有已生成的内容，保存到消息队列中
      if (aiChatState.streamContent && aiChatState.streamContent.trim()) { 
        const terminatedChatId = Date.now().toString() + '_ai_terminated';
        setAiAssistantQueue(prev => [...prev, {
          type: 'chat' as const,
          data: {
            type: 'ai' as const,
            content: aiChatState.streamContent + ' [已终止]', // 添加标记表示被手动终止
            timestamp: new Date().toISOString()
          },
          id: terminatedChatId,
          time: Date.now()
        }].sort((a, b) => a.time - b.time));
      }

      // 重置AI状态
      resetAiChatState();

      // 停止后滚动到底部
      scrollAiChatToBottom();
    } else if (aiChatState.isActive && aiChatState.type === 'auto') {
      message.warning('当前正在自动回复客户消息，无法手动终止');
    } else {
      message.warning('当前没有进行中的AI对话');
    }
  };

  // AI文件上传处理
  const handleAiFileUpload = async (file: File) => {
    // 检查文件类型
    if (!validateFileType(file)) {
      message.error(getFileTypeErrorMessage());
      return false;
    }
    
    // 检查文件大小
    if (!validateFileSize(file, 10)) {
      message.error(getFileSizeErrorMessage(10));
      return false;
    }

    // 检查总上传文件大小
    const totalSize = aiUploadedFiles.reduce((sum, f) => sum + (f.size || 0), 0) + file.size;
    if (totalSize > 10 * 1024 * 1024) {
      message.error('所有已上传文件总大小不能超过10M，请删除部分文件后再上传。');
      return false;
    }

    // 设置上传状态
    setUploadStatus({ isUploading: true, fileName: file.name });

    try {
      const result = await uploadFile(file, currentCustomer?.session_id);
      
      const newFile = {
        id: Date.now(),
        name: result.filename || file.name,
        originalName: file.name,
        size: file.size,
        type: file.type,
        docId: result.docId,
        uploadedAt: new Date().toISOString(),
        serviceId: 'auto',
        sessionId: currentCustomer?.session_id || streamApiService.getSessionId(),
      };
      
      setAiUploadedFiles(prev => [...prev, newFile]);
      message.success({ content: `文件 ${file.name} 上传成功`, key: 'upload' });
    } catch (error) {
      console.error('Upload error:', error);
      message.error({
        content: `上传失败: ${error instanceof Error ? error.message : '未知错误'}`,
        key: 'upload'
      });
    } finally {
      setUploadStatus({ isUploading: false, fileName: '' });
    }
    
    return false;
  };

  // 移除AI上传的文件
  const handleRemoveAiFile = (fileId: number) => {
    setAiUploadedFiles(prev => prev.filter(file => file.id !== fileId));
  };

  // 滚动到底部
  const scrollToBottom = () => {
    if (chatMessagesRef.current) {
      chatMessagesRef.current.scrollTop = chatMessagesRef.current.scrollHeight;
    }
  };

  // 智能滚动左侧聊天：只有在用户接近底部且没有手动向上滚动时才自动滚动
  const smartScrollChat = useCallback(() => {
    // 使用 requestAnimationFrame 来优化滚动性能
    requestAnimationFrame(() => {
      if (!chatMessagesRef.current || chatScrolledUp) return;

      const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.current;
      const isNearBottom = scrollHeight - scrollTop - clientHeight < 100; // 距离底部100px内

      if (isNearBottom) {
        chatMessagesRef.current.scrollTop = scrollHeight;
      }
    });
  }, [chatScrolledUp]);

  // 强制滚动左侧聊天到底部（用于顾问发送消息时）
  const forceScrollChatToBottom = useCallback(() => {
    // 使用 requestAnimationFrame 来优化滚动性能
    requestAnimationFrame(() => {
      if (chatMessagesRef.current) {
        chatMessagesRef.current.scrollTop = chatMessagesRef.current.scrollHeight;
      }
    });
  }, []);

  // 处理左侧聊天区域用户滚动事件 - 使用防抖优化
  const handleChatScroll = useCallback(() => {
    if (!chatMessagesRef.current) return;

    const { scrollTop, scrollHeight, clientHeight } = chatMessagesRef.current;
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 150;

    // 只有当状态真正改变时才更新，避免不必要的重渲染
    setChatScrolledUp(prev => {
      const newValue = !isNearBottom;
      return prev !== newValue ? newValue : prev;
    });
  }, []);

  // 滚动AI聊天到底部 - 使用防抖优化
  const scrollAiChatToBottom = useCallback(() => {
    if (aiChatRef.current) {
      aiChatRef.current.scrollTop = aiChatRef.current.scrollHeight;
    }
  }, []);

  // 智能滚动：在AI回复时始终滚动到底部，其他时候只有在用户接近底部且没有手动向上滚动时才自动滚动
  const smartScrollAiChat = useCallback(() => {
    // 使用 requestAnimationFrame 来优化滚动性能
    requestAnimationFrame(() => {
      if (!aiChatRef.current) return;

      // 如果AI正在回复（自动回复或手动对话），则强制滚动到底部
      if (isAutoReplying || isManualChatting) {
        aiChatRef.current.scrollTop = aiChatRef.current.scrollHeight;
      }
    });
  }, [isAutoReplying, isManualChatting]);

  // 处理用户滚动事件 - 使用防抖优化
  const handleAiChatScroll = useCallback(() => {
    if (!aiChatRef.current) return;
    const { scrollTop, scrollHeight, clientHeight } = aiChatRef.current;
    const isNearBottom = scrollHeight - scrollTop - clientHeight < 150;
    // 只有当状态真正改变时才更新，避免不必要的重渲染
    setUserScrolledUp(prev => {
      const newValue = !isNearBottom;
      return prev !== newValue ? newValue : prev;
    });
  }, [isAutoReplying, isManualChatting]);

  // 使用useRef来跟踪组件是否已卸载，防止内存泄漏
  const isMountedRef = useRef(true);
  
  // 在组件卸载时清理所有定时器的引用
  const timersRef = useRef<Set<NodeJS.Timeout>>(new Set());
  
  // 安全的定时器创建函数，会自动清理
  const createSafeTimeout = useCallback((callback: () => void, delay: number): NodeJS.Timeout => {
    const timeoutId = setTimeout(() => {
      if (isMountedRef.current) {
        callback();
      }
      timersRef.current.delete(timeoutId);
    }, delay);
    
    timersRef.current.add(timeoutId);
    return timeoutId;
  }, []);

  // 优化：使用 useMemo 来缓存滚动函数，避免频繁创建
  const debouncedScrollAiChatToBottom = useMemo(() => {
    let timeoutId: NodeJS.Timeout | null = null;
    return () => {
      if (timeoutId) {
        clearTimeout(timeoutId);
        timersRef.current.delete(timeoutId);
      }
      timeoutId = createSafeTimeout(() => {
        if (aiChatRef.current) {
          aiChatRef.current.scrollTop = aiChatRef.current.scrollHeight;
        }
      }, 50);
    };
  }, [createSafeTimeout]);


  // 监听AI助手相关状态变化，自动滚动到底部
  useEffect(() => {
    if (aiAssistantQueue.length > 0 || 
        isAutoReplying || 
        autoReplyStreamContent || 
        isManualChatting || 
        aiStreamReply) {
      debouncedScrollAiChatToBottom();
    }
  }, [
    aiAssistantQueue.length,
    isAutoReplying,
    autoReplyStreamContent,
    isManualChatting,
    aiStreamReply,
    debouncedScrollAiChatToBottom
  ]);

  // 监听手动thinking状态变化，自动滚动到底部 - 使用防抖优化
  useEffect(() => {
    if (isManualReasoning || manualThinkingContent || isWaitingForManualThinking) {
      debouncedScrollAiChatToBottom();
    }
  }, [isManualReasoning, manualThinkingContent, isWaitingForManualThinking, debouncedScrollAiChatToBottom]);

  // 监听自动回复thinking状态变化，自动滚动到底部 - 使用防抖优化
  useEffect(() => {
    if (isAutoReplyReasoning || autoReplyThinkingContent || isWaitingForAutoThinking) {
      debouncedScrollAiChatToBottom();
    }
  }, [isAutoReplyReasoning, autoReplyThinkingContent, isWaitingForAutoThinking, debouncedScrollAiChatToBottom]);

  // 监听深度思考开关变化，重置thinking相关状态
  useEffect(() => {
    // 重置所有thinking相关状态
    setIsManualReasoning(false);
    setManualThinkingContent('');
    setIsAutoReplyReasoning(false);
    setAutoReplyThinkingContent('');
    setIsWaitingForAutoThinking(false);
    setIsWaitingForManualThinking(false);
    
    // 清空thinking callbacks
    thinkingCallbacksRef.current = null;
    
    console.log(`深度思考模式切换为: ${deepThinkingEnabled ? '开启(Mock)' : '开启(Real)'}`);
  }, [deepThinkingEnabled]);

  // 处理键盘事件
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };



  // 新增：用于强制重置资产配置上传文件
  const [allocationPageKey, setAllocationPageKey] = useState(0);
  const [clearAssetFiles, setClearAssetFiles] = useState(false);

  // 重置资产文件清理标志
  useEffect(() => {
    if (clearAssetFiles) {
      setClearAssetFiles(false);
    }
  }, [clearAssetFiles]);

  // 清除会话历史
  const handleClearChatHistory = async () => {
    try {
      // 调用API删除会话内存
      if (currentCustomer?.session_id) {
        const abortController = new AbortController();
        
        const response = await fetch(`/langchain-backend/memory/session/${currentCustomer.session_id}`, {
          method: 'DELETE',
          signal: abortController.signal
        });
        
        if (!response.ok) {
          throw new Error('删除会话失败');
        }
      }
      
      // 检查组件是否还在挂载状态
      if (!isMountedRef.current) return;
      
      // 清空AI助手相关状态
      setAiAssistantQueue([]);
      setAiStreamReply('');
      setIsManualChatting(false);
      setIsAutoReplying(false);
      setAutoReplyStreamContent('');
      setAiChatInput('');
      setAiUploadedFiles([]);
      setIsAutoReplyReasoning(false); // 重置自动回复reasoning状态
      setIsManualReasoning(false); // 重置手动对话reasoning状态
      setAutoReplyThinkingContent(''); // 重置思考内容
      setManualThinkingContent(''); // 重置思考内容
      setIsWaitingForAutoThinking(false); // 重置等待思考状态
      setIsWaitingForManualThinking(false); // 重置等待思考状态
      
      // 停止正在进行的流式API请求
      streamApiService.stopStream();
      
      message.success('会话历史已清除');
    } catch (error) {
      // 忽略因组件卸载导致的取消请求错误
      if (error instanceof Error && error.name === 'AbortError') {
        return;
      }
      
      console.error('清除会话历史失败:', error);
      
      // 检查组件是否还在挂载状态
      if (isMountedRef.current) {
        message.error('清除会话历史失败');
      }
    }
  };

  // 获取SOP分析
  useEffect(() => {
    const abortController = new AbortController();
    
    const fetchSopAnalysis = async () => {
      // 只要有客户和理财师信息就触发SOP分析
      if (!currentCustomer || !currentManager) {
        setSopAnalysisResult(null);
        return;
      }

      setIsSopLoading(true);
      try {
        const params: SopAnalysisRequest = {
          query: "", // 使用默认查询
          mode: isDeepSop ? 'dynamic' : 'preset',
          session_id: currentCustomer.session_id || '', // 确保使用客户的 session_id
          user_name: currentCustomer.name,
        };
        
        // 添加AbortController来支持请求取消
        const response = await fetch('/langchain-backend/sop/analyze', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(params),
            signal: abortController.signal
        });

        if (!response.ok) {
            const errorData = await response.json().catch(() => null);
            throw new Error(`HTTP error! status: ${response.status}, message: ${errorData?.detail || response.statusText}`);
        }

        const result: ApiSopAnalysisResponse = await response.json();
        
        // 检查组件是否还在挂载状态
        if (!isMountedRef.current) return;
        
        if (result.success && result.full_chain) {
          // 将API返回的数据结构转换为前端UI所需的数据结构
          const transformedResult: SopAnalysisResponse = {
            success: true,
            chain_id: result.chain_id,
            chain_name: result.name,
            nodes: result.full_chain.map(apiNode => ({
              id: apiNode.order.toString(),
              name: apiNode.node,
              type: apiNode.stage,
              status: apiNode.order === result.current_node
                ? 'active'
                : apiNode.order < result.current_node
                  ? 'completed'
                  : 'pending',
              content: '', // content字段暂时为空
            })),
          };
          setSopAnalysisResult(transformedResult);
          setSelectedChainId(transformedResult.chain_id);
        } else {
          setSopAnalysisResult(null);
          console.error('SOP Analysis failed or returned invalid data:', result);
        }
      } catch (error) {
        // 忽略因组件卸载导致的取消请求错误
        if (error instanceof Error && error.name === 'AbortError') {
          return;
        }
        
        console.error('Failed to fetch SOP analysis:', error);
        
        // 检查组件是否还在挂载状态
        if (isMountedRef.current) {
          setSopAnalysisResult(null);
        }
      } finally {
        // 检查组件是否还在挂载状态
        if (isMountedRef.current) {
          setIsSopLoading(false);
        }
      }
    };

    fetchSopAnalysis();
    
    return () => {
      abortController.abort();
    };
  }, [currentCustomer, currentManager, isDeepSop]);

  // 监听聊天区域滚动事件
  useEffect(() => {
    const scrollContainer = chatMessagesRef.current;
    if (!scrollContainer) return;

    const handleScroll = (e: Event) => {
      const target = e.target as HTMLDivElement;
      if (target.scrollTop + target.clientHeight === target.scrollHeight) {
        setChatScrolledUp(true);
      } else if (target.scrollTop === 0) {
        setChatScrolledUp(false);
      }
    };
    
    scrollContainer.addEventListener('scroll', handleScroll);
    return () => {
      scrollContainer.removeEventListener('scroll', handleScroll);
    };
  }, []);

  // 添加Drawer状态
  const [sopDrawerVisible, setSopDrawerVisible] = useState(false);
  // 添加下一步建议面板折叠状态
  const [sopPanelCollapsed, setSopPanelCollapsed] = useState(false);

  // 优化：缓存客户聊天消息列表，减少重渲染
  const chatMessagesJsx = useMemo(() => {
    return messages.map((msg, index) => (
      <div key={`${msg.id}-${index}`} className={`flex ${msg.type === 'advisor' ? 'justify-end' : 'justify-start'}`}>
        <div className={`message-bubble ${msg.type} max-w-md px-4 py-3 rounded-lg ${msg.type === 'advisor'
            ? 'bg-blue-50 text-gray-800 rounded-br-sm shadow-sm'
            : 'bg-white text-gray-800 rounded-bl-sm shadow-sm'
          }`}>
          <div className="prose prose-sm max-w-none text-gray-800">
            <MarkdownRenderer content={msg.content} />
          </div>
          <div className={`text-xs mt-2 ${msg.type === 'advisor' ? 'text-blue-700' : 'text-gray-500'}`}>
            {msg.sender} · {formatTimestamp(msg.timestamp)}
          </div>
        </div>
      </div>
    ));
  }, [messages]);

  // 在组件内添加新的状态
  const [sopChains, setSopChains] = useState<Array<{ chain_id: string; name: string }>>([]);
  const [showSopSelect, setShowSopSelect] = useState(false);

  // 获取SOP chains列表
  useEffect(() => {
    if (isDeepSop) return; // 深度SOP模式不需要获取chains

    const abortController = new AbortController();

    const fetchSopChains = async () => {
      try {
        const response = await fetch('/langchain-backend/sop/chains', {
          method: 'GET',
          headers: {
            'Accept': 'application/json'
          },
          signal: abortController.signal
        });

        if (!response.ok) {
          throw new Error('Failed to fetch SOP chains');
        }

        const data = await response.json();
        
        // 检查组件是否还在挂载状态
        if (!isMountedRef.current) return;
        
        if (data.success && data.chains) {
          setSopChains(data.chains);
        }
      } catch (error) {
        // 忽略因组件卸载导致的取消请求错误
        if (error instanceof Error && error.name === 'AbortError') {
          return;
        }
        console.error('Error fetching SOP chains:', error);
      }
    };

    fetchSopChains();
    
    return () => {
      abortController.abort();
    };
  }, [isDeepSop]);

  // 同步选中的chain ID
  useEffect(() => {
    if (sopAnalysisResult?.chain_id) {
      setSelectedChainId(sopAnalysisResult.chain_id);
    }
  }, [sopAnalysisResult?.chain_id]);

  // 组件卸载时的清理工作
  useEffect(() => {
    return () => {
      // 标记组件已卸载
      isMountedRef.current = false;
      
      // 清理所有定时器
      timersRef.current.forEach(timeoutId => {
        clearTimeout(timeoutId);
      });
      timersRef.current.clear();
      
      // 停止所有正在进行的流式API请求
      streamApiService.stopStream();
    };
  }, []);

  // ==================== useEffect优化区域结束 ====================

  // 添加切换 chain 的处理函数
  const handleChainChange = async (chainId: string) => {
    setSelectedChainId(chainId);
    if (!currentCustomer || !currentManager) return;

    const abortController = new AbortController();
    setIsSopLoading(true);
    
    try {
      const params: SopAnalysisRequest = {
        query: "",
        mode: isDeepSop ? 'dynamic' : 'preset',
        session_id: currentCustomer.session_id || '',
        user_name: currentCustomer.name,
        chain_id: chainId
      };
      
      const response = await fetch('/langchain-backend/sop/analyze', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(params),
        signal: abortController.signal
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => null);
        throw new Error(`HTTP error! status: ${response.status}, message: ${errorData?.detail || response.statusText}`);
      }

      const result: ApiSopAnalysisResponse = await response.json();
      
      // 检查组件是否还在挂载状态
      if (!isMountedRef.current) return;
      
      if (result.success && result.full_chain) {
        const transformedResult: SopAnalysisResponse = {
          success: true,
          chain_id: result.chain_id,
          chain_name: result.name,
          nodes: result.full_chain.map(apiNode => ({
            id: apiNode.order.toString(),
            name: apiNode.node,
            type: apiNode.stage,
            status: apiNode.order === result.current_node
              ? 'active'
              : apiNode.order < result.current_node
                ? 'completed'
                : 'pending',
            content: '',
          })),
        };
        setSopAnalysisResult(transformedResult);
      }
    } catch (error) {
      // 忽略因组件卸载导致的取消请求错误
      if (error instanceof Error && error.name === 'AbortError') {
        return;
      }
      
      console.error('Failed to update SOP analysis:', error);
      
      // 检查组件是否还在挂载状态
      if (isMountedRef.current) {
        message.error('切换SOP策略失败');
      }
    } finally {
      // 检查组件是否还在挂载状态
      if (isMountedRef.current) {
        setIsSopLoading(false);
      }
    }
  };

  // 新增：监听AI流式内容变化，结合userScrolledUp控制自动滚动
  useEffect(() => {
    if (!userScrolledUp && aiChatState.streamContent) {
      debouncedScrollAiChatToBottom();
    }
  }, [aiChatState.streamContent, userScrolledUp, debouncedScrollAiChatToBottom]);

  return (
    <Layout className={`h-screen relative conversation-page ${isDragging ? 'select-none' : ''}`}>
      {/* 客户列表展开按钮 - 与返回首页按钮同一行 */}
      {!showCustomerList && (
        <div className="absolute top-6 left-4 z-50">
          <Tooltip title="展开客户列表" placement="right">
            <Button
              type="primary"
              shape="circle"
              size="small"
              icon={<UserOutlined />}
              onClick={() => setShowCustomerList(true)}
              className="shadow-lg bg-green-500 hover:bg-green-600 border-green-500"
            />
          </Tooltip>
        </div>
      )}

      {/* 左侧客户列表 */}
      {showCustomerList && (
        <Sider
          width={280}
          className="bg-white"
          style={{ overflow: 'hidden' }}
        >
          <div className="h-full flex flex-col">
            {/* 客户列表头部 */}
            <div className="p-4 border-b border-gray-200 bg-gray-50">
              <div className="flex items-center justify-between">
                <Title level={5} className="!mb-0 text-gray-800">客户列表</Title>
                <Button
                  type="text"
                  size="small"
                  onClick={() => setShowCustomerList(false)}
                  className="text-gray-500 hover:text-gray-700"
                >
                  收起
                </Button>
              </div>
              <div className="mt-1 text-xs text-gray-500">当前连接客户：{currentCustomerName}</div>
            </div>

            {/* 客户列表内容 */}
            <div className="flex-1 overflow-y-auto p-3">
              <List
                dataSource={customerList}
                renderItem={(customer) => (
                  <List.Item
                    className={`customer-list-item ${customer.id === currentCustomerId ? 'active' : ''
                      }`}
                    onClick={() => handleCustomerListClick(customer.id)}
                  >
                    <div className="flex items-center w-full">
                      <Badge
                        count={customer.unreadCount}
                        size="small"
                        className="mr-3"
                      >
                        <Avatar
                          size={40}
                          src={customer.avatar}
                          icon={<UserOutlined />}
                        />
                      </Badge>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-center justify-between">
                          <Text
                            strong={customer.id === currentCustomerId}
                            className={`text-sm truncate ${customer.id === currentCustomerId ? 'text-blue-600' : 'text-gray-900'
                              }`}
                          >
                            {customer.name}
                          </Text>
                          <Text className="text-xs text-gray-400 ml-2 flex-shrink-0">
                            {getTimeAgo(customer.lastMessageTime)}
                          </Text>
                        </div>

                        <div className="mt-1">
                          <Text
                            className="text-xs text-gray-500 truncate block"
                            style={{ maxWidth: '150px' }}
                          >
                            {formatMessageForDisplay(customer.lastMessage)}
                          </Text>
                        </div>

                        {customer.tags && customer.tags.length > 0 && (
                          <div className="mt-2">
                            {customer.tags.slice(0, 2).map((tag) => (
                              <Tag
                                key={tag}
                                className="text-xs border-gray-300 text-gray-600 bg-gray-100"
                              >
                                {tag}
                              </Tag>
                            ))}
                          </div>
                        )}
                      </div>
                    </div>
                  </List.Item>
                )}
              />
            </div>
          </div>
        </Sider>
      )}

      {/* 中间聊天区域 */}
      <Layout className="flex-1">
        <Content className="flex flex-col bg-white">
          {/* 聊天头部 */}
          <div className="p-4 chat-header">
            <div className="flex items-center justify-between">
              <div className="flex items-center">
                <Button
                  type="text"
                  icon={<ArrowLeftOutlined />}
                  onClick={() => navigate('/model-day')}
                  className={`mr-3 text-gray-600 hover:text-gray-800 ${!showCustomerList ? 'ml-12' : ''}`}
                  title="返回首页"
                />
                <Space>
                  <Avatar 
                    size="large" 
                    src={currentCustomer ? getCustomerAvatar(currentCustomer.id || 0, currentCustomer.name) : undefined}
                    icon={<UserOutlined />}
                  />
                  <div>
                    <Title level={4} className="!mb-0">{currentCustomer?.name}</Title>
                    <Space>
                      <Tag color="blue">{currentCustomer?.risk_level}</Tag>
                      <Tag color="green">{currentCustomer?.investment_experience}</Tag>
                    </Space>
                  </div>
                </Space>
              </div>
              <div className="flex items-center">
                <Space>
                  <div className="text-right mr-4">
                    <div className="text-sm text-gray-600">当前理财师 - {currentManager?.name || '未登录'}</div>
                  </div>
                  <Tag
                    icon={isWebSocketConnected ? <WifiOutlined /> : <DisconnectOutlined />}
                    color={isWebSocketConnected ? 'success' : 'error'}
                  >
                  </Tag>

                  {!showCustomerList && (
                    <Button
                      type="text"
                      icon={<UserOutlined />}
                      onClick={() => setShowCustomerList(true)}
                      className="text-gray-600 hover:text-gray-800"
                    >
                      客户列表
                    </Button>
                  )}
                  <Button
                    type="text"
                    icon={rightPanelVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                    onClick={() => setRightPanelVisible(!rightPanelVisible)}
                  >
                    AI助手
                  </Button>
                </Space>
              </div>
            </div>
          </div>

          {/* 消息区域 */}
          <div className="flex-1 relative bg-gray-50" style={{ minHeight: 0 }}>
            {isLoadingMessages ? (
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                <Spin size="large" />
                <div className="mt-3 text-gray-600">加载消息历史中...</div>
              </div>
            ) : (
              <div 
                ref={chatMessagesRef} 
                className="absolute inset-0 overflow-y-auto p-4 chat-messages-scroll-container scroll-container" 
                onScroll={handleChatScroll}
              >
                <div className="space-y-4">
                  {messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-full text-center py-20">
                      <Text className="text-lg font-medium text-gray-600">等待客户发送消息</Text>
                      <div className="mt-2 text-sm text-gray-500">
                        <div>{currentCustomer?.name}正在线上，等待发送第一条消息</div>
                      </div>
                    </div>
                  ) : (
                    chatMessagesJsx
                  )}
                </div>
              </div>
            )}

            {/* 回到底部按钮 - 左侧聊天区域 */}
            {chatScrolledUp && (
              <div className="absolute bottom-20 right-4">
                <Button
                  type="primary"
                  shape="circle"
                  size="small"
                  icon={<div className="text-xs">↓</div>}
                  onClick={() => {
                    scrollToBottom();
                    setChatScrolledUp(false);
                  }}
                  title="回到底部"
                  className="shadow-lg"
                />
              </div>
            )}
          </div>

          {/* 输入区域 */}
          <div className="p-4 chat-input-area">
            <div className="flex gap-2">
              <TextArea
                value={messageInput}
                onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setMessageInput(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="输入消息..."
                autoSize={{ minRows: 1, maxRows: 4 }}
                className="flex-1"
                disabled={aiChatState.isActive && aiChatState.type === 'auto'}
              />
              <Button
                type="primary"
                icon={<SendOutlined />}
                onClick={handleSendMessage}
                disabled={!messageInput.trim() || (aiChatState.isActive && aiChatState.type === 'auto')}
              >
                发送
              </Button>
            </div>
          </div>
        </Content>
      </Layout>

      {/* 右侧面板 */}
      {rightPanelVisible && (
        <Sider width={rightPanelWidth} className="bg-white right-panel relative">
          {/* 拖拽手柄 */}
          <div
            className={`absolute left-0 top-0 w-1 h-full cursor-col-resize z-10 
              ${isDragging ? 'bg-blue-500' : 'bg-transparent hover:bg-gray-300'} 
              transition-colors duration-200`}
            onMouseDown={handleMouseDown}
            style={{ marginLeft: '-2px' }}
          >
            <div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 w-1 h-8 bg-gray-400 rounded opacity-0 hover:opacity-100 transition-opacity duration-200" />
          </div>
          <div className="h-full flex flex-col">
            <Tabs
              activeKey={activeTab}
              onChange={setActiveTab}
              className="h-full flex flex-col"
              tabBarStyle={{
                paddingLeft: '4px',
                paddingRight: '4px',
                marginBottom: 0,
                backgroundColor: '#f8f9fa',
                borderRadius: '8px 8px 0 0'
              }}
              items={[
                {
                  key: 'business-guidance',
                  label: '经营引导',
                  icon: <RobotOutlined />,
                  children: (
                    <div className="h-full flex flex-col" style={{ height: 'calc(100vh - 116px)' }}>
                      {/* AI智能回复区域 */}
                      <div className="flex-1 p-4 min-h-0" style={{ height: 'calc(100% - 200px)' }}>
                        <Card
                          size="small"
                          title={
                            <div className="flex items-center justify-between">
                              <span>AI对话助手</span>
                              <div className="flex items-center gap-2">
                                <Button
                                  type="text"
                                  size="small"
                                  title="清除会话历史"
                                  icon={<DeleteOutlined />}
                                  onClick={handleClearChatHistory}
                                  className="text-gray-500 hover:text-red-500"
                                />
                                <RobotOutlined />
                              </div>
                            </div>
                          }
                          className="h-full flex flex-col"
                          styles={{ body: {
                            padding: '0',
                            height: '100%',
                            overflow: 'hidden',
                            flex: '1',
                            display: 'flex',
                            flexDirection: 'column'
                          } }}
                        >
                          <div className="relative flex-1 h-full">
                            <div 
                              ref={aiChatRef} 
                              className="absolute inset-0 overflow-y-auto p-3 ai-chat-scroll-container scroll-container" 
                              onScroll={handleAiChatScroll}
                            >
                              {/* 始终显示AI助手消息队列和流式回复 */}
                              {(aiAssistantQueue.length > 0 || isAutoReplying || (autoReplyStreamContent && autoReplyStreamContent.trim()) || (aiStreamReply && aiStreamReply.trim())) ? (
                                <div className="space-y-2">
                                  {/* 显示时间排序的消息队列 */}
                                  {aiAssistantQueue.map((item) => {
                                    if (item.type === 'chat') {
                                      const message = item.data;

                                      // 分割消息 - 使用智能分割组件
                                      if (message.type === 'ai' && (message.content.includes('[DIVIDER]') || message.content.includes('\n\n'))) {
                                        return (
                                          <SmartSegmentedMessageRenderer
                                            key={item.id}
                                            content={message.content}
                                            itemId={item.id}
                                            onSendSegment={handleSendAiReply}
                                            onCopySegment={handleCopyAiReply}
                                          />
                                        );
                                      }
                                      return (
                                        <div key={item.id} className={`flex ${message.type === 'user' ? 'justify-end' : 'justify-start'}`}>
                                          <div className={`max-w-xs px-3 py-2 rounded-lg ${
                                            message.type === 'user'
                                              ? 'bg-gray-100 text-gray-800 border border-gray-200'
                                              : message.type === 'customer'
                                                ? 'bg-blue-50 text-blue-900 border border-blue-200'
                                                : 'bg-white text-gray-800 border border-gray-200'
                                          }`}>
                                            {/* 文件显示 */}
                                            {message.files && message.files.length > 0 && (
                                              <div className="mb-2">
                                                {message.files.map((file, fileIndex) => (
                                                  <div key={fileIndex} className="flex items-center gap-2 p-2 bg-white rounded border">
                                                    <PictureOutlined className="text-blue-500" />
                                                    <div className="flex-1 text-xs">
                                                      <div className="font-medium text-gray-700 truncate" title={file.originalName || file.name}>
                                                        {file.originalName || file.name}
                                                      </div>
                                                      <div className="text-gray-500">{formatFileSize(file.size)}</div>
                                                    </div>
                                                  </div>
                                                ))}
                                              </div>
                                            )}
                                            <div className="text-sm prose prose-sm max-w-none">
                                              <MarkdownRenderer content={message.content} />
                                            </div>
                                            <div className="text-xs text-gray-500 mt-1">
                                              {message.type === 'user' ? (currentManager?.name || '理财师') : message.type === 'customer' ? '客户消息' : 'AI助手'} · {formatTimestamp(message.timestamp)}
                                            </div>
                                            {message.type === 'ai' && (
                                              <div className="flex gap-1 mt-2">
                                                <Button
                                                  type="primary"
                                                  size="small"
                                                  onClick={() => handleSendAiReply(message.content)}
                                                  icon={<SendOutlined />}
                                                >
                                                  发送
                                                </Button>
                                                <Button
                                                  size="small"
                                                  onClick={() => handleCopyAiReply(message.content)}
                                                  icon={<CopyOutlined />}
                                                >
                                                  复制
                                                </Button>
                                              </div>
                                            )}
                                          </div>
                                        </div>
                                      );
                                    }
                                    return null;
                                  })}

                                  {/* 统一的AI思考状态显示 */}
                                  {aiChatState.isActive && (aiChatState.isReasoning || aiChatState.isWaitingForThinking || !aiChatState.hasReceivedFirstChunk) && (
                                    <div className="flex justify-start">
                                      <ThinkingProcess 
                                        type={aiChatState.type || 'auto'} 
                                        mode={deepThinkingEnabled ? 'mock' : 'realtime'} // 反转逻辑
                                        query={aiChatState.type === 'auto' 
                                          ? (messages[messages.length - 1]?.content || '')
                                          : (aiAssistantQueue.filter(item => item.type === 'chat' && item.data.type === 'user').pop()?.data.content || '')
                                        }
                                        customerInfo={currentCustomer}
                                        // realtime模式的外部状态
                                        isThinking={aiChatState.isReasoning}
                                        thinkingContent={aiChatState.thinkingContent}
                                        isWaitingForThinking={aiChatState.isWaitingForThinking}
                                      />
                                    </div>
                                  )}

                                  {/* 统一的流式内容显示 - 只有在收到第一个有效chunk后才显示 */}
                                  {(() => {
                                    // 只在正在流式输出、已收到第一个有效chunk且有实际内容时显示
                                    if (aiChatState.isActive && aiChatState.hasReceivedFirstChunk && aiChatState.streamContent && aiChatState.streamContent.trim()) {
                                      const hasMultipleSegments = aiChatState.streamContent.includes('[DIVIDER]') || aiChatState.streamContent.includes('\n\n');
                                      
                                      if (hasMultipleSegments) {
                                        return (
                                          <StreamingSegmentedRenderer 
                                            content={aiChatState.streamContent}
                                            onSendSegment={handleSendAiReply}
                                            onCopySegment={handleCopyAiReply}
                                          />
                                        );
                                      } else {
                                        // 根据type显示不同的样式和文案
                                        const isAutoType = aiChatState.type === 'auto';
                                        const bgColor = isAutoType ? 'bg-green-50 border-green-300' : 'bg-blue-50 border-blue-300';
                                        const spinnerColor = isAutoType ? 'border-green-500' : 'border-blue-500';
                                        const textColor = isAutoType ? 'text-green-600' : 'text-blue-600';
                                        const loadingText = isAutoType ? 'AI正在自动分析客户问题...' : 'AI正在生成内容...';
                                        
                                        return (
                                          <div className="flex justify-start">
                                            <div className={`max-w-xs px-3 py-2 rounded-lg ${bgColor} text-gray-800 border`}>
                                              <div className="flex items-center gap-2 mb-2">
                                                <div className={`animate-spin w-3 h-3 border-2 ${spinnerColor} border-t-transparent rounded-full`}></div>
                                                <span className={`text-xs ${textColor}`}>
                                                  {loadingText}
                                                </span>
                                              </div>
                                              <div className="text-sm prose prose-sm max-w-none">
                                                <MarkdownRenderer content={aiChatState.streamContent} />
                                              </div>
                                            </div>
                                          </div>
                                        );
                                      }
                                    }
                                    
                                    return null;
                                  })()}
                                </div>
                              ) : (
                                <div className="flex-1 flex items-center justify-center">
                                  <div className="text-center">
                                    <Text type="secondary" className="text-sm block mb-2">
                                      在下方输入框中与AI助手开始对话
                                    </Text>
                                    <Text type="secondary" className="text-xs text-gray-400">
                                      当客户发来消息时，AI会自动生成回复建议
                                    </Text>
                                  </div>
                                </div>
                              )}
                            </div>

                            {/* 回到底部按钮 */}
                            {userScrolledUp && (
                              <div className="absolute bottom-2 right-2 z-10">
                                <Button
                                  type="primary"
                                  shape="circle"
                                  size="small"
                                  icon={<div className="text-xs">↓</div>}
                                  onClick={() => {
                                    scrollAiChatToBottom();
                                    setUserScrolledUp(false);
                                  }}
                                  title="回到底部"
                                  className="shadow-lg"
                                />
                              </div>
                            )}
                          </div>
                        </Card>
                      </div>

                      {/* 下一步建议面板 - 固定在底部 */}
                      <div className="flex-shrink-0 border-t border-gray-200 bg-white">
                        <Card
                          size="small"
                          title={
                            <div className="flex items-center justify-between w-full">
                              <div className="flex items-center gap-4">
                                <span className="font-semibold text-gray-800">下一步建议</span>
                                <div className="flex items-center gap-2">
                                  <Text type="secondary" className="text-xs">Deep SOP</Text>
                                  <Switch
                                    checked={isDeepSop}
                                    onChange={setIsDeepSop}
                                    size="small"
                                    loading={isSopLoading}
                                  />
                                </div>
                              </div>
                              <div className="flex items-center gap-2">
                                <Button 
                                  type="link" 
                                  size="small"
                                  onClick={() => setSopDrawerVisible(true)}
                                  className="text-blue-500 hover:text-blue-600"
                                >
                                  详情
                                </Button>
                                <Button 
                                  type="link" 
                                  size="small"
                                  onClick={() => setSopPanelCollapsed(!sopPanelCollapsed)}
                                  className="text-gray-500 hover:text-gray-700"
                                  icon={sopPanelCollapsed ? <EyeOutlined /> : <EyeInvisibleOutlined />}
                                >
                                </Button>
                              </div>
                            </div>
                          }
                          className="border-0 rounded-none shadow-sm"
                          styles={{
                            header: {
                              borderBottom: '1px solid #f0f0f0',
                              background: 'linear-gradient(to right, #fafafa, #f5f5f5)'
                            },
                            body: {
                              padding: sopPanelCollapsed ? '0' : '16px',
                              background: '#fafafa',
                              height: sopPanelCollapsed ? '0' : '194px', // 折叠时高度为0
                              overflowY: sopPanelCollapsed ? 'hidden' : 'auto',
                              transition: 'all 0.3s ease-in-out'
                            }
                          }}
                        >
                          {sopPanelCollapsed ? (
                            <div className="flex items-center justify-center h-8 text-gray-500 text-sm">
                              {isSopLoading ? 'SOP策略分析中...' : 
                               sopAnalysisResult && sopAnalysisResult.success && sopAnalysisResult.nodes && sopAnalysisResult.nodes.length > 0 ? 
                               '点击展开查看建议' : '暂无SOP建议'}
                            </div>
                          ) : (
                            <>
                              {isSopLoading ? (
                                <div className="flex items-center justify-center h-full">
                                  <Spin tip="SOP策略分析中..." />
                                </div>
                              ) : sopAnalysisResult && sopAnalysisResult.success && sopAnalysisResult.nodes && sopAnalysisResult.nodes.length > 0 ? (
                                <div className="flex flex-col gap-4">
                                  {/* 只显示当前节点和下一个节点 */}
                                  {(() => {
                                    const activeNodeIndex = sopAnalysisResult.nodes.findIndex(node => node.status === 'active');
                                    if (activeNodeIndex === -1) return null;

                                    const nodesToShow = sopAnalysisResult.nodes.slice(
                                      activeNodeIndex,
                                      activeNodeIndex + (activeNodeIndex === sopAnalysisResult.nodes.length - 1 ? 1 : 2)
                                    );

                                    return nodesToShow.map(node => (
                                      <div
                                        key={node.id}
                                        className={`flex items-start gap-2 cursor-pointer transition-all duration-200 p-2 rounded hover:bg-blue-50 `}
                                        onClick={() => handleSopNodeClick(node.name)}
                                        title={`点击发送"${node.name}"给AI助手`}
                                      >
                                        {/* 状态指示器 */}
                                        <div className="mt-1.5 relative">
                                          {node.status === 'active' ? (
                                            <>
                                              <div className="w-2 h-2 bg-blue-500 rounded-full"></div>
                                              <div className="absolute top-0 left-0 w-2 h-2 bg-blue-500 rounded-full animate-ping opacity-75"></div>
                                            </>
                                          ) : node.status === 'completed' ? (
                                            <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                                          ) : (
                                            <div className="w-2 h-2 border-2 border-blue-500 rounded-full bg-white"></div>
                                          )}
                                        </div>
                                        {/* 节点内容 */}
                                        <div className="flex-1">
                                          <div className="text-blue-600 font-semibold text-sm hover:text-blue-700">{node.name}</div>
                                          <div className="text-gray-800 text-sm mt-0.5">{node.type}</div>
                                        </div>
                                        {/* 点击提示图标 */}
                                        <div className="mt-1.5 opacity-60 hover:opacity-100 transition-opacity">
                                          <SendOutlined className="text-xs text-gray-400" />
                                        </div>
                                      </div>
                                    ));
                                  })()}
                                </div>
                              ) : (
                                <div className="flex items-center justify-center h-full text-gray-500">
                                  暂无SOP建议
                                </div>
                              )}
                            </>
                          )}
                        </Card>

                        {/* SOP详情抽屉 */}
                        <Drawer
                          title={
                            <div className="flex items-center justify-between">
                              <span>经营思路</span>
                            </div>
                          }
                          placement="right"
                          width={500}
                          onClose={() => setSopDrawerVisible(false)}
                          open={sopDrawerVisible}
                        >
                          {isSopLoading ? (
                            <div className="flex items-center justify-center h-full">
                              <Spin tip="SOP策略分析中..." />
                            </div>
                          ) : sopAnalysisResult && sopAnalysisResult.success && sopAnalysisResult.nodes && sopAnalysisResult.nodes.length > 0 ? (
                            <>
                              <div className="mb-6 text-left">
                                {/* 标题和搜索图标在同一行 */}
                                <div className="flex items-center justify-between mb-2">
                                  <Text strong className="text-lg text-blue-600">
                                    {isDeepSop ? "Deep SOP" : sopAnalysisResult.chain_name}
                                  </Text>
                                  {!isDeepSop && (
                                    <Tooltip title="打开策略搜索" placement="left">
                                      <Button
                                        type={showSopSelect ? "primary" : "text"}
                                        icon={<SearchOutlined />}
                                        onClick={() => setShowSopSelect(!showSopSelect)}
                                        size="small"
                                      />
                                    </Tooltip>
                                  )}
                                </div>
                                {/* 搜索选择框 */}
                                {!isDeepSop && showSopSelect && (
                                  <div className="mb-4">
                                    <Select
                                      value={selectedChainId || undefined}
                                      onChange={(value) => {
                                        handleChainChange(value);
                                        setShowSopSelect(false); // 选择后自动关闭选择框
                                      }}
                                      style={{ width: '100%' }}
                                      placeholder="请选择SOP策略"
                                      loading={isSopLoading}
                                      showSearch
                                      filterOption={(input, option) => {
                                        const name = option?.children?.toString() || '';
                                        return name.toLowerCase().includes(input.toLowerCase());
                                      }}
                                      optionFilterProp="children"
                                    >
                                      {sopChains.map(chain => (
                                        <Option key={chain.chain_id} value={chain.chain_id}>
                                          {chain.name}
                                        </Option>
                                      ))}
                                    </Select>
                                  </div>
                                )}
                              </div>
                              <div className="relative pl-8">
                                {/* 垂直线 */}
                                <div className="absolute left-4 top-0 bottom-0 w-[2px] bg-gray-200"></div>
                                
                                {/* 步骤列表 */}
                                <div className="space-y-8">
                                  {sopAnalysisResult.nodes.map((node, index) => (
                                    <div key={node.id} className="relative">
                                      {/* 步骤指示器 */}
                                      <div className="absolute -left-8 flex items-center justify-center w-8 h-8">
                                        {node.status === 'completed' ? (
                                          <div className="w-8 h-8 rounded-full bg-green-500 flex items-center justify-center text-white">
                                            ✓
                                          </div>
                                        ) : node.status === 'active' ? (
                                          <div className="relative">
                                            <div className="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white">
                                              {index + 1}
                                            </div>
                                            <div className="absolute top-0 left-0 w-8 h-8 rounded-full bg-blue-500 animate-ping opacity-75"></div>
                                          </div>
                                        ) : (
                                          <div className="w-8 h-8 rounded-full border-2 border-gray-300 bg-white flex items-center justify-center text-gray-500">
                                            {index + 1}
                                          </div>
                                        )}
                                      </div>

                                      {/* 步骤内容 */}
                                      <div className={`pl-6 ${
                                        node.status === 'active' 
                                          ? 'p-4 bg-blue-50 rounded-lg border border-blue-100' 
                                          : ''
                                      }`}>
                                        <div className="mb-1">
                                          <Text className={`text-sm ${
                                            node.status === 'completed' 
                                              ? 'text-green-600' 
                                              : node.status === 'active'
                                                ? 'text-blue-600'
                                                : 'text-gray-400'
                                          }`}>
                                            STEP {index + 1}
                                          </Text>
                                        </div>
                                        <div className="mb-1">
                                          <Text strong className={`text-base ${
                                            node.status === 'completed'
                                              ? 'text-green-700'
                                              : node.status === 'active'
                                                ? 'text-blue-700'
                                                : 'text-gray-500'
                                          }`}>
                                            {node.name}
                                          </Text>
                                        </div>
                                        <div>
                                          <Text className={`text-sm ${
                                            node.status === 'completed'
                                              ? 'text-green-600'
                                              : node.status === 'active'
                                                ? 'text-blue-600'
                                                : 'text-gray-400'
                                          }`}>
                                            {node.type}
                                          </Text>
                                        </div>
                                        {node.status === 'active' && (
                                          <div className="mt-2 text-xs text-blue-500">
                                            当前进行中
                                          </div>
                                        )}
                                      </div>
                                    </div>
                                  ))}
                                </div>
                              </div>
                            </>
                          ) : (
                            <div className="flex items-center justify-center h-full text-gray-500">
                              暂无SOP建议
                            </div>
                          )}
                        </Drawer>
                      </div>

                      {/* AI助手输入区域 - 固定在最底部 */}
                      <div className="flex-shrink-0 border-t border-gray-200 bg-white ai-assistant-input-container">
                        {/* 增强功能开关 */}
                        <div className="flex items-center gap-6 ai-feature-toggles">
                          <div
                            className={`flex items-center gap-2 cursor-pointer transition-all duration-200 ${deepThinkingEnabled
                                ? 'ai-feature-enabled'
                                : 'ai-feature-disabled'
                              }`}
                            onClick={() => setDeepThinkingEnabled(!deepThinkingEnabled)}
                          >
                            <div className={`ai-feature-icon ${deepThinkingEnabled ? 'enabled' : 'disabled'}`}>
                              <BulbOutlined />
                            </div>
                            <span className="text-xs font-medium">深度思考</span>
                          </div>
                          <div
                            className={`flex items-center gap-2 cursor-pointer transition-all duration-200 ai-feature-enabled`}
                          >
                            <div className={`ai-feature-icon enabled`}>
                              <CloudOutlined />
                            </div>
                            <span className="text-xs font-medium">联网搜索</span>
                          </div>
                        </div>

                        {/* 上传状态提示 */}
                        {uploadStatus.isUploading && (
                          <div className="mb-2 px-3 py-2 bg-blue-50 rounded-md border border-blue-200">
                            <div className="flex items-center gap-2">
                              <div className="animate-spin w-4 h-4 border-2 border-blue-500 border-t-transparent rounded-full"></div>
                              <span className="text-sm text-blue-700">
                                正在上传: {uploadStatus.fileName}
                              </span>
                            </div>
                          </div>
                        )}

                        {/* 已上传文件显示 */}
                        {aiUploadedFiles && aiUploadedFiles.length > 0 && (
                          <div className="mb-2 p-2 bg-gray-50 rounded border">
                            <div className="text-xs text-gray-600 mb-1">已上传文件:</div>
                            <div className="space-y-1">
                              {aiUploadedFiles.map((file) => (
                                <div key={file.id} className="flex items-center gap-2 text-xs">
                                  <PictureOutlined className="text-blue-500" />
                                  <span className="flex-1 truncate" title={file.originalName || file.name}>
                                    {file.originalName || file.name}
                                  </span>
                                  <Button
                                    type="text"
                                    size="small"
                                    onClick={() => handleRemoveAiFile(file.id)}
                                    className="text-gray-400 hover:text-red-500 p-0"
                                    icon={<CloseOutlined />}
                                    title="移除文件"
                                  />
                                </div>
                              ))}
                            </div>
                          </div>
                        )}

                        {/* 输入框和按钮 */}
                        <div className="flex gap-2">
                          {/* 文件上传按钮 */}
                          <Button
                            icon={<CloudUploadOutlined />}
                            onClick={() => aiFileInputRef.current?.click()}
                            disabled={aiChatState.isActive || uploadStatus.isUploading}
                            title="上传文件（支持PDF、Word、PPT、Excel、图片等）"
                            className="flex-shrink-0"
                          />

                          <TextArea
                            value={aiChatInput}
                            onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setAiChatInput(e.target.value)}
                            placeholder="与AI助手对话..."
                            autoSize={{ minRows: 1, maxRows: 3 }}
                            onPressEnter={(e: React.KeyboardEvent<HTMLTextAreaElement>) => {
                              if (!e.shiftKey) {
                                e.preventDefault();
                                handleAiChatSend();
                              }
                            }}
                            disabled={aiChatState.isActive || uploadStatus.isUploading}
                            className="flex-1"
                          />

                          {/* 发送/终止按钮 */}
                          {aiChatState.isActive && aiChatState.type === 'manual' ? (
                            <Button
                              danger
                              icon={<StopOutlined />}
                              onClick={handleStopAiReply}
                              title="终止手动AI对话"
                              className="flex-shrink-0"
                              disabled={uploadStatus.isUploading}
                            />
                          ) : (
                            <Button
                              type="primary"
                              icon={<SendOutlined />}
                              onClick={handleAiChatSend}
                              disabled={!aiChatInput.trim() || aiChatState.isActive || uploadStatus.isUploading}
                              title={aiChatState.isActive ? "AI正在思考或回复中，请稍等" : "Enter 发送 | Shift + Enter 换行"}
                              className="flex-shrink-0"
                            />
                          )}
                        </div>

                        {/* 隐藏的文件输入 */}
                        <input
                          ref={aiFileInputRef}
                          type="file"
                          accept=".pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.jpg,.jpeg,.png,.txt,.csv,.md"
                          style={{ display: 'none' }}
                          onChange={(e) => {
                            const file = e.target.files?.[0];
                            if (file) {
                              handleAiFileUpload(file);
                            }
                            e.target.value = '';
                          }}
                        />
                      </div>
                    </div>
                  )
                },
                {
                  key: 'investment-advisor',
                  label: '资产配置',
                  icon: <BarChartOutlined />,
                  children: (
                    <div className="h-full overflow-hidden" style={{ height: 'calc(100vh - 116px)' }}>
                      <AssetAllocationPage
                        key={allocationPageKey}
                        currentCustomer={currentCustomer as Customer}
                        clearUploadedFiles={clearAssetFiles}
                        deepThinkingEnabled={deepThinkingEnabled}
                        thinkingCallbacks={thinkingCallbacksRef.current}
                        onSendToUser={(content: string) => {
                          // 发送分析结果给客户
                          const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
                          if (wsUserId && chatWebSocketService.isConnected()) {
                            chatWebSocketService.sendChatMessage(wsUserId, content);

                            // 添加到消息列表
                            const newMessage: LocalMessage = {
                              id: generateLocalMessageId(),
                              type: 'advisor',
                              content: content,
                              timestamp: new Date().toISOString(), // 使用ISO格式
                              sender: currentManager?.name || '理财师',
                              originalTimestamp: Date.now()
                            };

                            setMessages(prev => [...prev, newMessage]);
                            createSafeTimeout(() => forceScrollChatToBottom(), 100);
                          } else {
                            message.error('WebSocket连接断开，无法发送消息');
                          }
                        }}
                      />
                    </div>
                  )
                },
                {
                  key: 'marketing-scenarios',
                  label: '营销',
                  icon: <CommentOutlined />,
                  children: (
                    <div className="h-full overflow-y-auto" style={{ height: 'calc(100vh - 116px)' }}>
                      <div className="mb-4 p-4">
                        <Title level={5} className="!mb-2">营销</Title>
                        <Text type="secondary" className="text-sm">
                          根据当前客户画像，以下营销场景可能更适合:
                        </Text>
                      </div>
                      <MarketingScenarios
                        currentCustomer={currentCustomer as Customer}
                        deepThinkingEnabled={deepThinkingEnabled}
                        thinkingCallbacks={thinkingCallbacksRef.current}
                        onSendToChat={(content: string) => {
                          // 发送营销话术到聊天框
                          const wsUserId = customerService.getCustomerWebSocketId(currentCustomer);
                          if (wsUserId && chatWebSocketService.isConnected()) {
                            chatWebSocketService.sendChatMessage(wsUserId, content);

                            // 添加到消息列表
                            const newMessage: LocalMessage = {
                              id: generateLocalMessageId(),
                              type: 'advisor',
                              content: content,
                              timestamp: new Date().toISOString(), // 使用ISO格式
                              sender: currentManager?.name || '理财师',
                              originalTimestamp: Date.now()
                            };

                            setMessages(prev => [...prev, newMessage]);
                            createSafeTimeout(() => forceScrollChatToBottom(), 100);
                          } else {
                            message.error('WebSocket连接断开，无法发送消息');
                          }
                        }}
                      />
                    </div>
                  )
                },
                {
                  key: 'customer-profile',
                  label: '画像',
                  icon: <IdcardOutlined />,
                  children: (
                    <div className="h-full overflow-hidden" style={{ height: 'calc(100vh - 116px)' }}>
                      <CustomerProfilePage customer={currentCustomer as Customer} />
                    </div>
                  )
                }
              ]}
            />
          </div>
        </Sider>
      )}

    </Layout>
  );
} 